﻿using System;
using System.Data;
using System.Drawing;

using HsTec.Mobile.Green.BLL;
using HsTec.Mobile.Green.Util;
using Baimasoft.Manage.SqlServerDAL;


public partial class PowerWarning_AuthenticationBenchmark : System.Web.UI.Page {
    ForecastBusinessBLL bll = new ForecastBusinessBLL();

    HsTec.Mobile.Green.DAL.ForecastBusinessDAL MyFB = new HsTec.Mobile.Green.DAL.ForecastBusinessDAL();

    Param MyP = new Param();

    protected void Page_Load(object sender, EventArgs e) {
        if ((string)Session["Baimasoft_Pers_ID"] == null) {
            Response.Redirect("../Logon.aspx");
        }
        if (!IsPostBack) {
            BindsltProvince();
            sltsYear.Value = DateTime.Now.Year.ToString();
            sltsMonth.Value = string.Format("{0:D2}", DateTime.Now.Month);
        }
    }
    protected void SaveData_ServerClick(object sender, EventArgs e) {
        #region 新版本

        #region 1.计算当月修正比例

        //	单位业务量耗电（2009年9月）=耗电量（2009年9月）/总业务量（2009年9月）
        //	修正比例（2010年9月）= 单位业务量耗电（2009年9月）/单位业务量耗电(全年)（2009年）
        //	业务量表取自rt_Traffic  耗电量rt_EnergyConsumption
        //sBusinessPowerUnit 单位业务量耗电

        //sCorrectionRatio 修正比例

        //string sCorrectionRatio = SQLHelper.ExecuteString("select cast('" + sBusinessPowerUnit + "' as decimal(20, 4))/((select sum(cast(Power as decimal(20, 4))) from rt_EnergyConsumption where Years like '" + sltsYear.Value.Substring(0, 4) + "%')/(select sum(cast(Value as decimal(20, 4))) from rt_TDTraffic where Years like '" + sltsYear.Value.Substring(0, 4) + "%'))");

        #endregion

        #region 2.计算警戒线A

        //单位业务量能耗变化率*往年单位业务量能耗（2009年）=全年预警值；
        //全年预警值*修正比例=单位业务量耗电警戒值A
        //修正比例（8月） = 单位业务量耗电（2009.8）/单位业务量耗电全年（2009）；
        //注：单位业务量能耗变化率是上面通过三目标导向分析计算获得的
        //sYearAlarmValue 全年预警值

        DateTime dYearLast = DateTime.Parse(sltsYear.Value + "-" + sltsMonth.Value + "-01").AddYears(-1);
        //往年单位业务量能耗 sTraffictmp
        string sPDCH = SQLHelper.ExecuteString("select sum(Value) from rt_PDCH where substring(Years,1,4) = '" + dYearLast.ToString("yyyy") + "' and Area_ID='41'");
        string sPhone = SQLHelper.ExecuteString("select sum(Value) from rt_Telephone where substring(Years,1,4) = '" + dYearLast.ToString("yyyy") + "' and Area_ID='41'");
        string sTD = SQLHelper.ExecuteString("select sum(Value) from rt_TDTraffic where substring(Years,1,4) = '" + dYearLast.ToString("yyyy") + "' and Area_ID='41'");
        double dTraffictmp = (Double.Parse(String.IsNullOrEmpty(sPDCH) ? "0" : sPDCH) +
                        Double.Parse(String.IsNullOrEmpty(sPhone) ? "0" : sPhone) +
                        Double.Parse(String.IsNullOrEmpty(sTD) ? "0" : sTD));
        if (dTraffictmp == 0) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sltsYear.Value + "年业务量为空，请先导入业务量数据！');</script>");
            return;
        }
        //往年单位业务量能耗 dBusinessPowerUnit
        string sPower = SQLHelper.ExecuteString("select sum(Power) from rt_EnergyConsumption where substring(Years,1,4) = '" + dYearLast.ToString("yyyy") + "' and Area_ID='41'");
        if (String.IsNullOrEmpty(sPower)) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sltsYear.Value + "年耗电量为空，请先导入耗电量数据！');</script>");
            return;
        }
        double dPower = Double.Parse(sPower);
        double dBusinessPowerUnit = dPower / dTraffictmp * 10000;
        //全年预警值 = 单位业务量能耗变化率*往年单位业务量能耗
        string sBussinessRate = SQLHelper.ExecuteString("select top 1 BusinessRate from tb_ChangeRate where Years='" + sltsYear.Value + "'");
        if (String.IsNullOrEmpty(sBussinessRate)) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('省公司单位业务量能耗变化率未录入！');</script>");
            return;
        }
        double dBussinessRate = Double.Parse(sBussinessRate);
        double sYearAlarmValue = (1 - dBussinessRate) * dBusinessPowerUnit;
        //单位业务量耗电警戒值A
        //修正比例
        string sFixedRatio = SQLHelper.ExecuteString("select MonthRatio from tb_FixedRatio where Years='" + sltsYear.Value + sltsMonth.Value + "'");
        if (String.IsNullOrEmpty(sFixedRatio)) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sltsYear.Value + "年" + sltsMonth.Value + "月的修正比例未录入！');</script>");
            return;
        }
        double dFixedRatio = Double.Parse(sFixedRatio);
        //全年预警值*修正比例
        double dA = sYearAlarmValue * dFixedRatio;
        lblA.Text = dA.ToString("0") + " (度/万Erl)";
        #endregion

        //3.计算警戒值B
        //（求和（9月份各地市耗电标杆值*9月份各地市实际业务量值）+省公司9月预测耗电量+1-8月份累计耗电量）/1-9月份累计耗电量

        // 3.1 汇总 9月份各地市耗电标杆值*9月份各地市实际业务量值
        double dtmp = 0.0;
        DataView areadv = SQLHelper.ExecuteDataView("select ID,[Name] from Area where ParentID='10' and ID!='41' and ID!='39'");
        for (int i = 0; i < areadv.Count; i++) {
            string sMark = SQLHelper.ExecuteString("select MarkValue from tb_ForecastBusinessNew where Years='" + sltsYear.Value + sltsMonth.Value + "' and Area_ID='" + areadv[i][0].ToString() + "'");
            string sTraffic = SQLHelper.ExecuteString("select Value from rt_Traffic where Area_ID='" + areadv[i][0].ToString() + "' and Years='" + sltsYear.Value + sltsMonth.Value + "'");

            string sPDCHd = SQLHelper.ExecuteString("select sum(Value) from rt_PDCH where Years = '" + sltsYear.Value + sltsMonth.Value + "' and Area_ID='" + areadv[i][0].ToString() + "'");
            string sPhoned = SQLHelper.ExecuteString("select sum(Value) from rt_Telephone where Years = '" + sltsYear.Value + sltsMonth.Value + "' and Area_ID='" + areadv[i][0].ToString() + "'");
            string sTDd = SQLHelper.ExecuteString("select sum(Value) from rt_TDTraffic where Years = '" + sltsYear.Value + sltsMonth.Value + "' and Area_ID='" + areadv[i][0].ToString() + "'");
            double dTraffictmpd = (Double.Parse(String.IsNullOrEmpty(sPDCHd) ? "0" : sPDCHd) +
                            Double.Parse(String.IsNullOrEmpty(sPhoned) ? "0" : sPhoned) +
                            Double.Parse(String.IsNullOrEmpty(sTDd) ? "0" : sTDd));
            sTraffic = dTraffictmpd.ToString();
            if (String.IsNullOrEmpty(sMark)) {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + areadv[i][1].ToString() + "的标杆值未录入！');</script>");
                return;
            }
            if (String.IsNullOrEmpty(sTraffic)) {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + areadv[i][1].ToString() + "的实际业务量未录入！');</script>");
                return;
            }
            dtmp += double.Parse(sMark) * double.Parse(sTraffic) / 10000;
        }
        //获取省公司预测值
        string sProvince = SQLHelper.ExecuteString("select Value from tb_ProvinceForecast where Years='" + sltsYear.Value + sltsMonth.Value + "'");
        if (String.IsNullOrEmpty(sProvince)) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('省公司" + sltsYear.Value + "年" + sltsMonth.Value + "月的预测值耗电值未录入！');</script>");
            return;
        }
        double dProvince = Double.Parse(sProvince);
        //1-8月份累计耗电量
        DateTime dLastMonth = DateTime.Parse(sltsYear.Value + "-" + sltsMonth.Value + "-01").AddMonths(-1);
        string sLastPower = SQLHelper.ExecuteString("select sum(Power) from rt_EnergyConsumption where Years>='" + dLastMonth.ToString("yyyy") + "01' and  Years<='" + dLastMonth.ToString("yyyyMM") + "' and Area_ID ='41'");
        if (String.IsNullOrEmpty(sLastPower)) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请导入各地区耗电量值！');</script>");
            return;
        }
        //求和（9月份各地市耗电标杆值*9月份各地市实际业务量值）+省公司9月预测耗电量
        double dD = (dtmp + dProvince);
        lblPowers.Text = (dtmp + dProvince).ToString("0") + "度";
        dtmp = dtmp + dProvince + double.Parse(sLastPower);   //各地市标杆值*业务量 + 省公司预测 + 1至上一月累计值
        labCumulativePowers.Text = dtmp.ToString("0.00");
        //1-9月份全省累计业务量
        sPDCH = SQLHelper.ExecuteString("select sum(Value) from rt_PDCH where Years >= '" + sltsYear.Value + "01' and Years <= '" + sltsYear.Value + sltsMonth.Value + "' and Area_ID='41'");
        sPhone = SQLHelper.ExecuteString("select sum(Value) from rt_Telephone where Years >= '" + sltsYear.Value + "01' and Years <= '" + sltsYear.Value + sltsMonth.Value + "' and Area_ID='41'");
        sTD = SQLHelper.ExecuteString("select sum(Value) from rt_TDTraffic where Years >= '" + sltsYear.Value + "01' and Years <= '" + sltsYear.Value + sltsMonth.Value + "' and Area_ID='41'");
        double dTrafficPrivance = (Double.Parse(String.IsNullOrEmpty(sPDCH) ? "0" : sPDCH) +
                        Double.Parse(String.IsNullOrEmpty(sPhone) ? "0" : sPhone) +
                        Double.Parse(String.IsNullOrEmpty(sTD) ? "0" : sTD));
        if (dTrafficPrivance == 0) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('省公司业务量信息未导入！');</script>");
            return;
        }
        double dB = dtmp / dTrafficPrivance * 10000;
        lblB.Text = dB.ToString("0") + " (度/万Erl)";
        //4.计算警戒值C
        //	（2010年预测耗电量 – 某月之前的所有耗电量）*（2009年同月耗电/剩余月份总电量）
        string tmpWhere = String.Empty;
        if (sltsMonth.Value == "01") {
            tmpWhere = "Years>='" + sltsYear.Value + "01' and Years<='" + sltsYear.Value + sltsMonth.Value + "' and Area_ID ='41'";
        }
        else {
            tmpWhere = "Years>='" + sltsYear.Value + "01' and Years<'" + sltsYear.Value + sltsMonth.Value + "' and Area_ID ='41'";
        }
        string sBeforeConsumption = SQLHelper.ExecuteString("select sum(Power) from rt_EnergyConsumption where " + tmpWhere);
        string sPowersForecast = SQLHelper.ExecuteString("select Powers from tb_ChangeRate where Years='" + sltsYear.Value + "'");
        if (String.IsNullOrEmpty(sPowersForecast)) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('未录入预测年耗电量值！');</script>");
            return;
        }
        double dRemain = double.Parse(sPowersForecast) - double.Parse(sBeforeConsumption);
        string sLastMonth = DateTime.Parse(sltsYear.Value + "-" + sltsMonth.Value + "-01").AddYears(-1).ToString("yyyyMM");
        string sMonthPower = SQLHelper.ExecuteString("select sum(Power) from rt_EnergyConsumption where Years='" + sLastMonth + "' and Area_ID ='41'");
        string sRemainLast = SQLHelper.ExecuteString("select sum(Power) from rt_EnergyConsumption where Years >='" + sLastMonth + "' and Years<='" + sLastMonth.Substring(0, 4) + "12' AND Area_ID='41'");
        if (String.IsNullOrEmpty(sRemainLast)) {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sLastMonth + "至" + sLastMonth.Substring(0, 4) + "的耗电量为空值，请导入相关数据！');</script>");
            return;
        }
        double dC = dRemain * double.Parse(sMonthPower) / double.Parse(sRemainLast);
        lblC.Text = dC.ToString("0") + "度";

        if (dA > dB) {
            lblResults.Text = "警戒值A>警戒值B";
        }
        else {
            lblResults.Text = "警戒值A<=警戒值B";
        }
        if (dC > dD) {
            lblResults.Text += "   警戒值C>警戒值D";
        }
        else {
            lblResults.Text += "   警戒值C<=警戒值D";
        }

        #endregion

        #region 老版本
        ////1.获取某月全省单位业务量耗电警戒值A
        ///string sYear = sltsYear.Value + sltsMonth.Value;
        //string sNowYear = DateTime.Now.ToString("yyyyMM");
        //if (sYear == sNowYear)
        //    iType = 1;
        ////1.1 获取某月的调整比例
        //string sProportion = bll.GetProportion(sYear, sltProvince.Value.Trim());
        //if (String.IsNullOrEmpty(sProportion))
        //{
        //    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('该月份调整比例未录入！');</script>");
        //    return;
        //}
        //string sA = bll.GetA(sYear, sltProvince.Value.Trim());
        //if (String.IsNullOrEmpty(sA))
        //{
        //    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('全省规划单位业务量耗电值未录入！');</script>");
        //    return;
        //}
        //Decimal tmpA = Decimal.Parse(sA) * Decimal.Parse(sProportion);
        //lblA.Text = tmpA.ToString("0.00") + " (度/erl)";
        ////1.2 该月各地市预测业务量
        //string sService = String.Empty;
        ////1.3 全省预测耗电量
        ////1.3.1 通过上月实际话务量
        //string sPowers = String.Empty;
        //int iBack = 0;
        //if (iType == 0)
        //{
        //    iBack = bll.GetServiceByFact(sltProvince.Value.Trim(), sYear, ref sService);
        //    if (iBack == 1)
        //    {
        //        sService = Convert.ToString(Math.Round(Convert.ToDecimal(sService) / 10000, 2));
        //        lblArea.Text = sService;
        //    }
        //    else
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sService + "该月的话音业务量、PDCH值未录入！');</script>");
        //        return;
        //    }
        //    iBack = bll.GetPowersByFact(sltProvince.Value.Trim(), sYear, ref sPowers);
        //    if (iBack == 1)
        //    {
        //        //省公司
        //        string sPower = bll.GetProvincePowers(sYear);
        //        if (sPower.Trim() == "" || sPower == null)
        //        {
        //            sPower = "0";
        //        }
        //        sPowers = Convert.ToString(Math.Round((Convert.ToDecimal(sPowers)) / 10000 + Convert.ToDecimal(sPower), 2));
        //        lblPowers.Text = sPowers;
        //    }
        //    else
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sPowers + "该月的单位业务量耗电标杆值和本月业务量值未录入！');</script>");
        //        return;
        //    }
        //}
        //else
        //{
        //    iBack = bll.GetServiceByForecast(sltProvince.Value.Trim(), sYear, ref sService);
        //    if (iBack == 1)
        //    {
        //        sService = Convert.ToString(Math.Round(Convert.ToDecimal(sService) / 10000, 2));
        //        lblArea.Text = sService;
        //    }
        //    else
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sService + "该月的预测话音业务量、预测PDCH值未录入！');</script>");
        //        return;
        //    }
        //    iBack = bll.GetPowersByForecast(sltProvince.Value.Trim(), sYear, ref sPowers);
        //    if (iBack == 1)
        //    {
        //        //string sPower = bll.GetProvincePowers(sYear);
        //        sPowers = Convert.ToString(Math.Round((Convert.ToDecimal(sPowers)) / 10000, 2));

        //        lblPowers.Text = sPowers;
        //    }
        //    else
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sPowers + "该月的单位业务量耗电标杆值和本月预测业务量值未录入！');</script>");
        //        return;
        //    }
        //}
        ////1.4 全省预测单位业务量耗电值B
        //Decimal tmpB = Decimal.Parse(sPowers);
        ////前一个月累计实际耗电量值
        //string sCumulativePowers = String.Empty;
        //sCumulativePowers = bll.GetCumulativePowers(sltProvince.Value.Trim(), sYear);
        //labCumulativePowers.Text = sCumulativePowers;
        //lblPowertmp.Text = sPowers;
        //sPowers = Convert.ToString(Math.Round(Convert.ToDecimal(sPowers) + Convert.ToDecimal(sCumulativePowers), 2));
        //lblPowers.Text = sPowers;
        ////累计业务量值
        //string sCumulativeService = String.Empty;
        //sCumulativeService = bll.GetCumulativeService(sltProvince.Value.Trim(), sYear);
        //labCumulativeService.Text = sCumulativeService;
        //tmpB = Convert.ToDecimal(sPowers) / Convert.ToDecimal(sCumulativeService);
        //lblB.Text = tmpB.ToString("0.00") + " (度/erl)";
        //if (tmpA >= tmpB)
        //    lblResults.Text = "全省单位业务量耗电警戒值A>=全省预测单位业务量耗电值B";
        //else
        //{
        //    lblResults.Text = "全省单位业务量耗电警戒值A<全省预测单位业务量耗电值B";
        //    lblResults.ForeColor = Color.Red;
        //    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('警告：警戒值A<预测耗电量值B！');</script>");
        //}
        #endregion
    }
    private void BindsltProvince() {
        sltProvince.DataTextField = "Name";
        sltProvince.DataValueField = "ID";
        sltProvince.DataSource = bll.GetProvince();
        sltProvince.DataBind();
        sltProvince.Items.Insert(0, "请选择县市区域...");
        sltProvince.Items[0].Value = "";
    }
}
